package com.zengyu.toiusuapplication;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.zengyu.toiusuapplication.Utils.SessionManager;
import com.zengyu.toiusuapplication.Utils.UserCacheManager;
import com.zengyu.toiusuapplication.api.ApiClient;
import com.zengyu.toiusuapplication.change.PasswordActivity;
import com.zengyu.toiusuapplication.model.User;
import com.zengyu.toiusuapplication.unload.UninstallReceiver;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private NavigationView navigationView;
    private BottomNavigationView bottomNavigationView;
    private UninstallReceiver uninstallReceiver;
    public static Long UserId;
    private TextView userNameTextView;
    private TextView emailTextView;
    private DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
        uninstallReceiver = new UninstallReceiver();  //卸载应用广播
        registerReceiver(uninstallReceiver, filter);
        setContentView(R.layout.activity_main);

        navigationView = findViewById(R.id.nav_view);
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        drawerLayout = findViewById(R.id.drawer_layout);

        // 缓存视图组件
        View headerView = navigationView.getHeaderView(0);
        userNameTextView = headerView.findViewById(R.id.userNameTextView);
        emailTextView = headerView.findViewById(R.id.emailTextView);
        navigationView.setNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.nav_home) {
                NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                        .navigate(R.id.homeFragment);
            } else if (id == R.id.nav_workbench) {
                NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                        .navigate(R.id.workbenchFragment);
            } else if (id == R.id.nav_profile) {
                NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                        .navigate(R.id.profileFragment);
            } else if (id == R.id.action_logut) {
                logout();
            } else if (id == R.id.action_marge){
                Intent intent = new Intent(this, PasswordActivity.class);
                startActivity(intent);
            }
            drawerLayout.closeDrawer(GravityCompat.START);   //抽屉左边弹出来的。弹出还是关闭。
            return true;
        });
        fetchUserInfo();
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        // 处理 Home Tab的标题和颜色
                        NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                        .navigate(R.id.homeFragment);
                        break;
                    case R.id.navigation_workbench:
                        // 处理 Workbench Tab
                        NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                        .navigate(R.id.workbenchFragment);
                        break;
                    case R.id.navigation_profile:
                        // 处理 Profile Tab
                        NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                        .navigate(R.id.profileFragment);
                        break;
                }
                return true;
            }
        });
        NavHostFragment.findNavController(getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment))
                .navigate(R.id.homeFragment);
    }

    public void openDrawer() {
        if (drawerLayout != null && !drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    protected void onResume() {
        //为了确保在应用运行期间 token 不会过期，可以在应用的某些关键地方定期检查 token 的过期时间。
        //例如，在每次 API 请求之前或在应用的某些生命周期方法中进行检查。
        super.onResume();
        SessionManager sessionManager = SessionManager.getInstance(this);
        if (!sessionManager.isTokenValid()) {
            // Token 过期，强制重新登录
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(uninstallReceiver); // 注销 BroadcastReceiver
    }


    // 从缓存加载用户信息的辅助方法
    private User loadUserFromCache() {
        UserCacheManager cacheManager = new UserCacheManager(this);
        return cacheManager.getUserInfo();
    }

    private void fetchUserInfo() {
        if (!isNetworkAvailable()) {
            Toast.makeText(this, "无网络连接", Toast.LENGTH_SHORT).show();
            // 尝试从缓存加载用户信息
            User cachedUser = loadUserFromCache();
            if (cachedUser != null) {
                userNameTextView.setText(cachedUser.getName());
                emailTextView.setText(cachedUser.getEmail());
                UserId = cachedUser.getId();
            } else {
                Toast.makeText(this, "无法加载用户信息，请检查网络", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // 假设缓存时间为 10 分钟
        long CACHE_DURATION = 10 * 60 * 1000; // 毫秒
        SessionManager sessionManager = new SessionManager(MainActivity.this);
        String token = sessionManager.getToken();
        if (sessionManager.isTokenValid() && !token.isEmpty()) {
            // 可以继续请求
            Call<User> call = ApiClient.getApiService().getUserInfo();
            call.enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    if (response.isSuccessful()) {
                        User user = response.body();
                        // 使用缓存的视图组件
                        if (user != null) {
                            userNameTextView.setText(user.getName());
                            emailTextView.setText(user.getEmail());
                            UserId = user.getId();
                            // 缓存用户信息并设置过期时间
                            UserCacheManager cacheManager = new UserCacheManager(MainActivity.this);
                            cacheManager.saveUserInfo(user, CACHE_DURATION); // 带过期时间的保存
                        }
                    } else {
                        Log.e("UserInfo", "Failed to fetch user info: code=" + response.code());
                        Toast.makeText(MainActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    Toast.makeText(MainActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                    User cachedUser = loadUserFromCache();
                    if (cachedUser != null) {
                        userNameTextView.setText(cachedUser.getName());
                        emailTextView.setText(cachedUser.getEmail());
                        UserId = cachedUser.getId();
                    }
                }
            });
        } else {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }

    //退出功能
    private void logout() {
        // 显示确认对话框
        new AlertDialog.Builder(this)
                .setTitle("确认退出")
                .setMessage("您确定要退出登录吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        performLogout();
                    }
                })
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .show();
    }

    private void performLogout() {
        SessionManager sessionManager = new SessionManager(this);
        sessionManager.clearAuthToken(); // 清除 token 等认证信息
        UserCacheManager userCacheManager = new UserCacheManager(this);
        userCacheManager.clearUserInfo(); // 清除本地缓存的用户信息
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_marge) {
            drawerLayout.openDrawer(GravityCompat.START);
            // 处理修改用户密码
            Intent intent = new Intent(this, PasswordActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_logut) {
            logout();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
